package com.atguigu.yygh.listener;

import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.mq.pojo.MqConst;
import com.atguigu.yygh.mq.service.RabbitService;
import com.atguigu.yygh.repository.ScheduleRepository;
import com.atguigu.yygh.service.ScheduleService;
import com.atguigu.yygh.vo.OrderMqVo;
import com.atguigu.yygh.vo.msm.MsmVo;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @description: rabbitmq监听器，监听order队列，消息的消费者
 * 拿到消息，改变mongodb中的剩余挂号数量
 * @author: 化一帆
 * @date: 2022/12/9 17:03
 * @version: v1.0
 */
@Component
public class HospitalReceiver {

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private ScheduleRepository scheduleRepository;

    //监听第一个队列
    //从队列取出消息的时候，需要创建监听器，绑定交换机和队列以及key
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ORDER, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_ORDER),
            key = {MqConst.ROUTING_ORDER}
    ))
    public void receiver(OrderMqVo orderMqVo) throws IOException {
        //下单成功，异步更新号源数
        Schedule schedule = scheduleService.getById(orderMqVo.getScheduleId());
        schedule.setReservedNumber(orderMqVo.getReservedNumber());
        schedule.setAvailableNumber(orderMqVo.getAvailableNumber());
        scheduleService.update(schedule);

        //向第二个队列发送消息
        //2.继续向MQ发送消息【此时需要发送预约成功的短信】，需要指定交换机和队列和key，以及消息对象的类型
        MsmVo msmVo = orderMqVo.getMsmVo();
        if(null != msmVo) {
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
        }
    }

    //监听第三个队列的消息
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_CANCEL_ORDER, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_CANCEL_ORDER),
            key = {MqConst.ROUTING_CANCEL_ORDER}
    ))
    public void listenQueue3(OrderMqVo mqVo){
        String scheduleId = mqVo.getScheduleId();//mg中排班id
        Schedule schedule = scheduleService.getById(scheduleId);
        schedule.setAvailableNumber(schedule.getAvailableNumber()+1);
        scheduleRepository.save(schedule);

        //向第二个队列发送消息
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM,MqConst.ROUTING_MSM_ITEM,mqVo.getMsmVo());
    }


}
